<template>
  <div>
    <div class='search-form-wrapper'>
      <h3 class='page-title'>数据筛选</h3>
      <Form
        :label-width='40'
        :model='searchForm'
        class='search-form'
        inline
        ref='searchForm'
      >
        <div>
          <FormItem label='姓名' prop='name'>
            <Input placeholder='请输入姓名' v-model='searchForm.name' />
          </FormItem>
          <FormItem label='岗位' prop='jobname'>
            <Input placeholder='请输入岗位' v-model='searchForm.jobname' />
          </FormItem>
          <FormItem label='公司' prop='departmentname'>
            <Input
              placeholder='请输入公司名称'
              v-model='searchForm.departmentname'
            />
          </FormItem>
        </div>
        <FormItem>
          <Button @click='handleResetSearchForm' class='reset-btn'>重置</Button>
          <Button @click='handleSearchClick' type='primary'>查询</Button>
        </FormItem>
      </Form>
    </div>
    <div class='table-title'>
        <Col span="6" class="table-title-button">
          <h3>人员列表</h3>
          <Button type='primary' @click="addDepartment">新增</Button>
        </Col>
      <div>
        <Button
          @click='handleAddStaff'
          type='primary'
          v-if='isShowAddStaffButton'
        >添加人员
        </Button
        >
        <!-- <Button>导出</Button>
        <Button>导入</Button>-->
        <Button @click='handleMuStopStaff' type='error'>禁用</Button>
      </div>
    </div>
    <Row>
      <Col :lg='{ span: 6 }' :md='{ span: 24 }' class='padding-right my-scollor'>
        <Tree :data='treeData' :render='renderContent'></Tree>
        <Spin fix v-if='treeLoading'></Spin>
      </Col>
      <Col :lg='{ span: 18 }' :md='{ span: 24 }' class='padding-left'>
        <Table
          :columns='tableColumns'
          :data='tableList'
          :loading='tableLoading'
          @on-selection-change='handleSelectChange'
          border
          ref='staffTable'
          stripe
        >
          <template slot='status' slot-scope='{ row }'>
            {{row.status=="AUTH_SUCCESS"?'已认证':'未认证'}}
            <Button type="primary" :loading="row.loading" shape="circle" size="small" icon="md-refresh"  @click="handleSwitchChange(row)">
        </Button>
            <!-- <i-switch
              shape="circle"
              :disabled='row.status=="AUTH_SUCCESS"'
              @on-change='handleSwitchChange(row)'
              size='large'
              v-model='row.status'
              true-value='AUTH_SUCCESS'
            >
              <span slot='open'>已认证</span>
              <span slot='close'>未认证</span>
            </i-switch> -->
          </template>
          <template slot='action' slot-scope='{ row }'>
            <Button
              @click="handleStaffEditClick(row.id, 'look')"
              size='small'
              style='margin-right: 2px'
              type='primary'
            >查看
            </Button
            >
            <Button
              @click="handleStaffEditClick(row.id, 'edit')"
              size='small'
              style='margin-right: 2px'
              type='primary'
            >编辑
            </Button
            >
            <Button
              @click='handleSignClick(row.id)'
              size='small'
              style='margin-right: 2px'
              type='primary'
            >认证
            </Button
            >
            <Button
              @click='handleStaffDeleteClick(row.id)'
              size='small'
              type='error'
            >删除
            </Button
            >
          </template>
        </Table>

        <div class='page-wrapper clearfix'>
          <Page
            :current='page'
            :total='total'
            @on-change='handlePageChange'
            @on-page-size-change='handlePageSizeChange'
            show-sizer
            show-total
          />
        </div>
      </Col>
    </Row>

    <ModalStaffDeparment
      :isEdit='modalDepartmentIsEdit'
      :oprNode='oprNode'
      @on-save-success='handleDepartmentSave'
      v-model='EditStaffDepartmentVisiable'
    />

    <ModalStaff
      :isEdit='modalStaffIsEdit'
      :oprStaffId='oprStaffId'
      :selectTreeNode='selectTreeNode'
      :title='modelTitle'
      @on-save-success='handleStaffSave'
      v-model='editStaffVisiable'
    />
    <ModalSign
      ref='ModalSign'
      :id='modalSignId'
      @on-save-success='handleStaffSave'
    />
  </div>
</template>

<script>
import ModalStaffDeparment from './modal-staff-deparment';
import ModalStaff from './modal-staff';
import ModalSign from './modal-sign';
import {
  departmentList,
  departmentDelete,
  getUserList,
  getUserListByDepartment,
  delUser,
  frozenAccount,
  switchStatus
} from '@/api/staff.js';

import { qysHeaders } from '@/api/qiyuesuo.js';

export default {
  components: {
    ModalStaffDeparment,
    ModalStaff,
    ModalSign
  },
  data () {
    return {
      modalSignId: 0,
      searchForm: {
        name: '',
        jobname: '',
        departmentname: ''
      },
      myValue: true,
      treeLoading: true,
      // tree结构数据
      treeData: [],
      selectTreeNode: {},
      index: 0,
      loading: false,

      // table数据
      tableColumns: [
        { type: 'selection', width: 55, align: 'center' },
        { title: '姓名', key: 'fullname', align: 'center' },
        { title: '账号', key: 'username', align: 'center' },
        { title: '公司', key: 'companyname', align: 'center' },
        { title: '项目部门', key: 'departmentname', align: 'center' },
        { title: '角色', key: 'rolename', align: 'center' },
        // { title: '岗位', key: 'jobname', align: 'center' },
        { title: '刷新认证状态', align: 'center', slot: 'status' },
        { title: '操作', slot: 'action', width: 235, align: 'center' }
      ],
      tableList: [],
      tableSelection: [],
      total: 100,
      page: 1,
      pageSize: 10,
      tableLoading: true,

      // 添加编辑部门弹窗
      EditStaffDepartmentVisiable: false,
      modalDepartmentIsEdit: false,
      oprNode: {},

      // 添加编辑员工弹窗
      editStaffVisiable: false,
      modalStaffIsEdit: false,
      oprStaffId: '',
      modelTitle: '添加员工'
    };
  },
  computed: {
    isShowAddStaffButton () {
      return JSON.stringify(this.selectTreeNode) !== '{}';
    }
  },
  watch: {
    // 关闭的添加编辑员工弹窗时候，重置数据
    EditStaffDepartmentVisiable: function (val) {
      if (!val) {
        this.modalDepartmentIsEdit = false;
        this.oprNode = {};
      }
    }
  },
  mounted () {
    this.getDepartmentList();
    this.getList();
  },
  methods: {
    addDepartment () {
      this.EditStaffDepartmentVisiable = true;
      this.modalDepartmentIsEdit = false;
    },
    async handleSwitchChange (row, index) {
      const userId = row.id;
      console.log(index, 'index');
      row.loading = true;
      const resp = await switchStatus(userId);
      const { code, data: data_states } = resp.data;
      if (code === 200 && data_states === 'AUTH_SUCCESS') {
        row.status = 'AUTH_SUCCESS';
        row.loading = false;
      } else {
        row.loading = false;
        row.status = 'FAIL';
        this.$Message.succ(resp.data.msg);
      }
      // console.log('resp', resp);
    },
    // 电子签名
    async handleSignClick (id) {
      this.modalSignId = id;
      console.log(this.$refs.ModalSign);
      this.$refs.ModalSign.show();
      this.$refs.ModalSign.getUser(id);

      let res = await qysHeaders();
      console.info(res.data);
    },
    async getDepartmentList () {
      const resp = await departmentList();
      this.treeLoading = false;
      // console.log('公司部门树 resp=>', resp);
      const treeData = resp.data.data;
      // 处理数据
      const handleTerrData = treeDate => {
        treeDate.forEach(node => {
          this.$set(node, 'nodeClick', false);
          // node.expand = true;
          if (node.children) {
            handleTerrData(node.children);
          }
        });
      };

      handleTerrData(treeData);
      this.treeData = treeData;
    },
    async getUserListByDepartment () {
      this.tableLoading = true;
      const data = {
        pageSize: this.pageSize,
        pageNum: this.page
      };
      if (JSON.stringify(this.selectTreeNode) !== '{}') {
        data.deparmentId = this.selectTreeNode.nodeId;
      }
      const resp = await getUserListByDepartment(data);
      this.tableLoading = false;

      this.total = resp.data.total;
      this.tableList = resp.data.data;
    },
    getRowAUTHSUCCESS (list) {
      list.forEach(item => {
        // item['isAUTH_SUCCESS'] = item.status === 'AUTH_SUCCESS';
        item['loading'] = false;
      });
      return list;
    },
    async getList () {
      this.tableLoading = true;
      const data = {
        pageSize: this.pageSize,
        pageNum: this.page
      };

      if (this.searchForm.name) {
        data.name = this.searchForm.name;
      }
      if (this.searchForm.jobname) {
        data.jobname = this.searchForm.jobname;
      }
      if (this.searchForm.departmentname) {
        data.departmentname = this.searchForm.departmentname;
      }

      const resp = await getUserList(data);
      this.tableLoading = false;
      this.total = resp.data.total;
      // console.log(resp.data.data, 'resp.data.dataresp.data.data');
      this.tableList = this.getRowAUTHSUCCESS(resp.data.data);
      console.log(this.tableList, 'this.tableListthis.tableList');
    },
    handleResetSearchForm () {
      this.$refs.searchForm.resetFields();
      this.getList();
    },
    handleSearchClick () {
      // 搜索的时候重置数据
      this.selectTreeNode = {};
      // 处理数据
      const handleTerrData = treeDate => {
        treeDate.forEach(node => {
          node.nodeClick = false;
          if (node.children) {
            handleTerrData(node.children);
          }
        });
      };
      handleTerrData(this.treeData);
      this.getList();
    },
    renderContent (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-flex',
            width: '100%',
            justifyContent: 'space-between'
          },
          class:
            data.nodeClick === true ? 'tree-item  level-click' : 'tree-item '
        },
        [
          h(
            'span',
            {
              style: {
                display: 'inline-flex',
                lineHeight: '20px',
                height: '20px',
                cursor: 'pointer',
                whiteSpace: 'normal',
                alignItems: 'center'
              },
              class: 'tree-text',
              on: {
                click: () => {
                  this.page = 1
                  this.selectTreeNode = node.node;
                  for (let i = 0; i < root.length; i++) {
                    root[i].node.nodeClick = false;
                  }
                  data.nodeClick = true;
                  this.$refs.searchForm.resetFields();
                  this.getUserListByDepartment();
                }
              }
            },

            [
              h('Icon', {
                props: {
                  type: 'ios-paper-outline'
                },
                style: {
                  margin: '0 5px',
                  fontSize: '16px',
                  verticalAlign: 'middle'
                }
              }),
              h(
                'span',
                {
                  style: {
                    // lineHeight: '1.4'
                  }
                },
                data.nodeName
              )
            ]
          ),
          h(
            'span',
            {
              style: {
                alignItems: 'center',
                marginRight: '30px'
              }
            },

            [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  size: 'small',
                  type: 'text'
                }),
                class: 'text-btn',
                style: {
                  color: 'rgb(90, 111, 206)',
                  padding: '0 3px 8px'
                },
                domProps: {
                  innerHTML: '增加'
                },
                on: {
                  click: async () => {
                    this.EditStaffDepartmentVisiable = true;
                    this.modalDepartmentIsEdit = false;
                    this.oprNode = node.node;
                  }
                }
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  size: 'small',
                  type: 'text'
                }),
                class: 'text-btn',
                style: {
                  color: 'rgb(90, 111, 206)',
                  padding: '0 3px 8px'

                },
                domProps: {
                  innerHTML: '编辑'
                },
                on: {
                  click: () => {
                    this.EditStaffDepartmentVisiable = true;
                    this.modalDepartmentIsEdit = true;
                    this.oprNode = node.node;
                  }
                }
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  size: 'small',
                  type: 'text'
                }),
                class: 'text-btn',
                style: {
                  color: '#ed4014',
                  padding: '0 3px 8px'
                },
                domProps: {
                  innerHTML: '删除'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '确认删除？',
                      content: '<p>数据删除后不可恢复，请确认是否删除数据？</p>',
                      loading: true,
                      onOk: async () => {
                        const id = node.node.nodeId;
                        const { data: { code, msg } } = await departmentDelete({ id });
                        this.$Message[code !== 200 ? 'error' : 'success'](msg);
                        this.getDepartmentList();
                        this.$Modal.remove();
                      }
                    });
                  }
                }
              })
            ]
          )
        ]
      );
    },
    handleSelectChange (selection) {
      this.tableSelection = selection;
    },
    handlePageChange (page) {
      this.page = page;
      this.getList();
    },
    handlePageSizeChange (pageSize) {
      this.pageSize = pageSize;
      this.getList();
    },
    handleDepartmentSave () {
      this.getDepartmentList();
    },
    handleStaffSave () {
      this.getList();
    },
    handleStaffEditClick (id, type) {
      if (type === 'look') {
        this.modelTitle = '查看员工';
      } else if (type === 'edit') {
        this.modelTitle = '编辑员工';
      } else {
        this.modelTitle = '添加员工';
      }

      this.oprStaffId = id;
      this.modalStaffIsEdit = true;
      this.editStaffVisiable = true;
    },
    handleStaffDeleteClick (id) {
      this.$Modal.confirm({
        title: '确认删除？',
        content: '<p>数据删除后不可恢复，请确认是否删除数据？</p>',
        loading: true,
        onOk: async () => {
          await delUser({ userId: String(id) });
          this.getList();
          this.$Modal.remove();
        }
      });
    },
    handleMuStopStaff () {
      if (this.tableSelection.length === 0) {
        this.$Message.warning('请选择需要操作的用户');
        return;
      }
      this.$Modal.confirm({
        title: '确认禁用？',
        content: '<p>请确认是否禁用选择用户？</p>',
        loading: true,
        onOk: async () => {
          const ids = this.tableSelection.map(item => item.id).join(',');
          const data = {
            frozen: 1,
            ids
          };
          await frozenAccount(data);
          this.getList();
          this.$Modal.remove();
          this.$Message.success('操作成功');
        }
      });
    },
    handleAddStaff () {
      this.modelTitle = '添加员工';
      this.modalStaffIsEdit = false;
      this.editStaffVisiable = true;
    }
  }
};
</script>

<style lang='less' scoped>
@import '../../../assets/css/hoverscollor.css';

.search-form-wrapper {
  border-bottom: 1px solid #dcdee2;
  margin-bottom: 10px;
}

.page-title {
  margin-bottom: 10px;
}

.search-form {
  display: flex;
  justify-content: space-between;

  .reset-btn {
    margin-right: 10px;
  }

  .ivu-form-item {
    margin-bottom: 10px;
  }

  > .ivu-form-item:last-child {
    margin-right: 0;
  }
}

.table-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  .ivu-btn {
    margin-left: 10px;
  }
  .table-title-button{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 40px;
  }
}

.page-wrapper {
  .ivu-page {
    float: right;
    margin: 10px 0;
  }
}

/deep/ .level-click {
  .tree-text {
    padding: 15px 8px;
    background: rgb(90, 111, 206);
    border-radius: 3px;
    color: #fff !important;
  }
}

/deep/ .tree-item {
  .ivu-btn {
    visibility: hidden;
  }
}

/deep/ .tree-item:hover {
  .tree-text {
    color: rgb(90, 111, 206);
  }

  .ivu-btn {
    visibility: visible;
  }
}

/deep/ .ivu-table-cell {
  padding-left: 10px;
  padding-right: 10px;
}

/deep/ .ivu-tree-arrow i {
  margin-bottom: 8px;
}

.text-btn {
  padding: "0 3px 10px";
}

</style>
